from myelin.Ns import MYELINS

from nodetypes.core.DocumentOrdering import OrderByKeys
from nodetypes.ntypes.Container.showContains.MML import Document, Transform


class Document(Document):
    
    def createContentContainer(self, context, node, locale):
        action = context.action
        acls = context.acls.checkNodeAcls
        
        model = context.model
        
        groupingId = model.rdf_value
        
        # get matching contained nodes
        nodes = []
        n_extend = nodes.extend
        
        for n in model.mParent:
            n_extend(
                n for n in n.mContains
                if groupingId in n.mGrouping and
                acls(n.rdf_domain, action)
            )
            
        for n in model.mTranslation_Of:            
            groupingId = n.rdf_value
            for n in n.mParent:
                for n in n.mContains:
                    if groupingId in n.mGrouping:
                        n_extend(
                            n for n in n.mTranslation
                            if locale in n.dcLanguage and
                            acls(n.rdf_domain, action)
                        )
        
        if nodes:
            OrderByKeys(model, nodes)
                
            # nodes without groupings
            self.createContainerNodes(
                context,
                node.xml_append(
                    node.xml_create_element(
                        u'a:grouping', MYELINS,
                        attributes = {
                            u'role'         : u'container',
                            u'key'          : u'node-grouping',
                            u'count'        : unicode(len(nodes)),
                        }
                    )
                ),
                nodes,
                context.defaults.document_root,
                model.rdf_join('dcLanguage')
            )
            
        return node
    

class Transform(Transform):
    
    newDocument = Document